# -*- coding:utf-8 -*-
'''
Created on 2014-4-16

@author: naruto
'''
import os
import os.path
print(os.getcwd())
import sys
sys.path.append('EncodeTable')
import re
import KDMacor

import  datetime
from curses.ascii import NUL
import LangConv
import codecs
class ConvertLang(object):
    '''
    classdocs
    '''
    listLocale=list()
    listBlack=list()
    def __init__(self):
        '''
        构造函数
        '''
    def subLocaleText(self,oldText,prefix1,prefix2):
        '''
        去除loc(@" 、"）
        '''
        len1=len(prefix1)
        len2=len(prefix2)
        oldText1=oldText.strip();
        lenText=len(oldText1)
        newText=oldText1[len1:lenText-len2]
        del lenText
        del oldText1
        return newText
    def checkFileType(self,filterStr,fileName):
        '''
        检测文件类型是否符合指定规则
        '''
        if '.' in fileName:
            file_type  = ',.'+fileName.rsplit('.',1)[1]+','
            if file_type in filterStr:
                return True
            else:
                return False 
        else:
            return False
    def checkNOFile(self,filterStr,fileName):
        '''
        检测文件是否在黑名单
        '''
        if fileName in filterStr:
            return True
        else:
            return False 
    def checkSearchDoc(self,filterStr,docName):
        '''
        检测是否需要搜索该目录
        '''
        docName1  = ','+docName+','
        if docName1 in filterStr:
            return False
        else:
            return True 
    def searchDocument(self,path):
        '''
        搜索目录
        '''
        try:
            filesCurrent=os.listdir(path)
        except:
            print('searchDocument error：'+path)
        else:
            print('searchDocument ing：'+path)
            for fileTemp in filesCurrent:
                filePath=os.path.join(path,fileTemp)        
                if(os.path.isdir(filePath) & self.checkSearchDoc(KDMacor.KD_CONVERT_NO_DOC, fileTemp)):
                    self.searchDocument(filePath)
                elif(self.checkFileType(KDMacor.KD_CONVERT_FILE_TYPE, filePath) & (self.checkNOFile(KDMacor.KD_CONVERT_NO_FILE, fileTemp)==False)):
                    self.readFile(filePath)
           
    def readFile(self,filePath):
        '''
        读取文件，获取符合LOC("XXX")格式的字符串
        '''
        try:
            file_object =codecs.open(filePath, 'r','utf-8','ignore')
        except:
            print('读取文件错误：'+filePath)
            del file_object
        else:
            print('正在读取文件：'+filePath)
            reObj1 = re.compile('LOC\(\@"*[^LOC]*"\)')
            for itemText in file_object.readlines():
                itemText1=itemText.replace('\n','').replace('\r','')
                if len(itemText1)==0:
                    continue
                temp=reObj1.findall(itemText1)
                for name in temp:
                    newText=self.subLocaleText(name,'LOC(@"','")')
                    if(newText in self.listLocale or newText in self.listBlack):
                        ''
                    else:
                        self.listLocale.append(newText)
                    del newText
                del itemText1
                del itemText
            file_object.close( )
            del file_object
            del reObj1
    
    def saveLocaleData(self,localeList,prefix):
        '''
        把多语言数据保存到文件里
        '''
        timerCurrent=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ;
        fileName=prefix+timerCurrent+'.txt'
        try:
            fileHandle =codecs.open (fileName, 'w','utf-8')
        except:
            print('保存到文件失败：'+fileName)
            del fileHandle
        else:
            for text in localeList:
                fileHandle.write('\"'+text+'\"=\"'+text+'\"'+';\n')  
            fileHandle.close()
            print('保存到文件成功:'+fileName)
            del fileHandle
            
    def saveHantLocaleData(self,localeList,prefix):
        '''
        把多语言数据保存到文件里
        '''
        timerCurrent=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ;
        fileName=prefix+timerCurrent+'.txt'
        try:
            fileHandle =codecs.open(fileName, 'w','utf-8')
        except:
            print('保存到文件失败：'+fileName)
            del fileHandle
        else:
            for text in localeList:
                textHant =LangConv.Converter('zh-hant').convert(text) 
                txtContent='\"'+text+'\"=\"'+textHant+'\"'+';\n';
#                 txtContent=txtContent.encode('utf-8')
                fileHandle.write(txtContent)
                del txtContent
                del text
            fileHandle.close()
            print('保存到文件成功：'+fileName)
            del fileHandle
            
    def canvertHantLang(self,listHans):
        '''
        转到到繁体
        '''
        listHant = list()
        for text in listHans:
            textHant =LangConv.Converter('zh-hant').convert(text.decode('utf-8')) 
            textHant = textHant.encode('utf-8')
            listHant.append(textHant)
            del textHant
            del text
        return listHant
    
    def loadBlackList(self,filePath):
        '''
        加载黑名单字符串（用于剔除以前版本就有的字符串）
        '''
        file_object=object()
        try:
            file_object = codecs.open (filePath, 'r','utf-8')
        except:
            print('加载黑名单字符串失败：'+filePath)
        else:
            for itemText in file_object.readlines():
                itemText1=itemText.replace(' ','')
                if len(itemText1)==0:
                    continue
                if '=' in itemText:
                    temp=itemText.split('=')
                    for name in temp:
                        newText=self.subLocaleText(name,'"','"')
                        if newText in self.listBlack:
                            ''
                        else:
                            self.listBlack.append(newText)
                        del newText
                del itemText1
                del itemText
            file_object.close( )
            print('加载黑名单字符串成功：'+filePath)
        del file_object




if __name__ == '__main__':
    print('请运行 main.py')